'use strict';
const FastScanner = require('../../lib/fastscan.js');
const util = require('../../lib/util.js');

module.exports = async (job, done, app) => {
  console.log('---------------------');
  const start = Date.now();
  const startstr = util.nowstr();
  const data = job.data;
  if (data) {
    const resultInfo = {};
    const where = {};
    if (data.source) {
      where.source = data.source;
    }
    const categorie = data.hasOwnProperty('categorie_id');
    const workerConfig = app.config.worker || { page_size: 100000, ConcurrentFindNum: 5 };
    let count = 0;
    if (categorie) {
      count = await app.defineWords(data.categorie_id).count({ where });
    } else {
      count = await app.model.TortWords.count({ where });
    }
    app.logger.info(`${data.sign}:find-count:${count}`);
    const pages = Math.ceil(count / workerConfig.page_size);
    for (let index = 0; index < pages; index += workerConfig.ConcurrentFindNum) {
      const queryArr = [];
      for (let num = 0; num < workerConfig.ConcurrentFindNum; num++) {
        if ((num + index) >= pages) {
          break;
        }
        if (categorie) {
          queryArr.push(await app.defineWords(data.categorie_id).findAll({
            attributes: [ 'word' ],
            where,
            limit: workerConfig.page_size,
            offset: workerConfig.page_size * Math.max(0, (index - 1 + num)),
            raw: true,
          }).then(list => {
            return list.map(ele => {
              return ele.word;
            });
          }));
        } else {
          queryArr.push(await app.model.TortWords.findAll({
            attributes: [ 'word' ],
            where,
            limit: workerConfig.page_size,
            offset: workerConfig.page_size * Math.max(0, (index - 1 + num)),
            raw: true,
          }).then(list => {
            return list.map(ele => {
              return ele.word;
            });
          }));
        }
      }
      const words = await Promise.all(queryArr).then(wordsList => {
        const arr = [];
        for (const wordArr of wordsList) {
          arr.push(...wordArr);
        }
        return arr;
      });
      const scanner = new FastScanner(words);
      for (const textInfo of data.texts) {
        const item = resultInfo[textInfo.key] || {};
        item.begin_hit_time = Date.now();
        Object.assign(item, { word: scanner.hits(textInfo.text) });
        item.end_hit_time = Date.now();
        resultInfo[textInfo.key] = item;
      }
    }
    await app.redis.set(`detection-result:${data.sign}`, JSON.stringify(resultInfo), 'EX', 48 * 60 * 60);
    if (data.callback_url) {
      for (const [ key, info ] of Object.entries(resultInfo)) {
        const respes = await app.erpPost('save_cite_tort_log', {
          json_content: JSON.stringify({
            goods_id: key,
            begin_hit_time: info.begin_hit_time,
            end_hit_time: info.end_hit_time,
            word: Object.keys(info.word),
          }),
        }).catch(err => {
          app.logger.error(`callback_url:save_cite_tort_log------error:${err.message}`);
          app.logger.error('callback_url:save_cite_tort_log------error sigin: %s', app.__token__);
        });
        try {
          app.logger.info(`callback_url:save_cite_tort_log-----respes:${JSON.stringify(respes)}`);
        } catch (err) {
          app.logger.info(`callback_url:save_cite_tort_log-----respes:${respes}`);
        }
      }
    }
    if (data.test_callback) {
      for (const [ key, info ] of Object.entries(resultInfo)) {
        console.log('json_content', JSON.stringify({
          goods_id: key,
          begin_hit_time: info.begin_hit_time,
          end_hit_time: info.end_hit_time,
          word: Object.keys(info.word),
        }));
      }
    }
    const end = Date.now();
    const endstr = util.nowstr();
    app.logger.info(`Sing任务执行：${data.sign}:开始时间(ms):${startstr} 完成时间(ms):${endstr}  处理时长:${end - start} ms 任务结果:${JSON.stringify(resultInfo)}`);
    return Promise.resolve(done());
  }
  return Promise.resolve();
};
